/**
 * Java Enterprise in a Nutshell, Third Edition, 
 * by Jim Farley and William Crawford 
 * with Prakash Malani, John G. Norman, and Justin Gehtland. 
 * Copyright 2006 O'Reilly Media, Inc., 0-596-10142-2.
 *  
 * Reworked by Vladimir Tarasov, 2009-08-26.
 * Tested with JDK 1.6.
 * The folder containing the class file should be on the CLASSPATH
 */
package tavl_rmi.accountmanager;

import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import tavl_rmi.account.Account;
import tavl_rmi.account.AccountImpl;

/**
 * AccountManagerImpl: Sample implementation of the AccountManager interface.
 * This streamlined example simply registers each account with the local registry,
 * and does the lookup for the remote client when getAccount() is called
 * or deletes an account with the given name. In a more realistic situation, the
 * manager would use a table (or a map) instead of the local registry to track
 * created account objects. For an example of using a map, see stateful WS.
 * This class is used in the factory RMI example.
 */
public class AccountManagerImpl
        extends UnicastRemoteObject implements AccountManager {

    /**
     * port number to access the registry
     */
    private int port;

    /**
     * Create and register some accounts in the beginning
     */
    public AccountManagerImpl(int port) throws RemoteException {
        this.port = port;
        newAccount("Fred");
        newAccount("Wilma");
    }

    public Account getAccount(String name) throws RemoteException {
        Registry reg = LocateRegistry.getRegistry(port);
        Account a = null;
        try {
            a = (Account) reg.lookup(name);
        } catch (Exception e) {
        }
        return a;
    }

    public boolean newAccount(String name) throws RemoteException {
        Registry reg = LocateRegistry.getRegistry(port);
        System.out.print("Registering new account " + name + "... ");
        Account newAcct = new AccountImpl(name);
        reg.rebind(newAcct.getName(), newAcct);
        System.out.println("done.");
        return true;
    }

    public boolean deleteAccount(String name) throws RemoteException, NotBoundException {
        Registry reg = LocateRegistry.getRegistry(port);
        System.out.print("Deleting account " + name + "... ");
        reg.unbind(name);
        System.out.println("done.");
        return true;
    }
}  